#! /bin/bash

set -e

function defaultgo {
	go $@\
		code.google.com/p/tasked/share\
		code.google.com/p/tasked/auth\
		code.google.com/p/tasked/htfile\
		code.google.com/p/tasked/htauth\
		code.google.com/p/tasked/htproc\
		code.google.com/p/tasked/keyval\
		code.google.com/p/tasked
}

function selfcert {
	key= cert=
	while :
	do
		case $1 in
		-key) shift; key=$1;;
		-cert) shift; cert=$1;;
		"") break;;
		*) shift;;
		esac
	done
	if [ ! "$key" -o ! "$cert" ]; then
		echo 'tsk selfcert -key <key-output-path> -cert <cert-output-path>'
		exit 1
	fi
	mkdir -p $(dirname $key)
	mkdir -p $(dirname $cert)
	openssl req -new -x509 -days 1095 -nodes -out "$cert" -keyout "$key"
}

function test {
	long=""
	while :
	do
		case $1 in
		-long) long="-test.long"; shift;;
		"") break;;
		*) shift;;
		esac
	done
	go install code.google.com/p/tasked/testproc
	go test -i code.google.com/p/tasked/share
	go test code.google.com/p/tasked/share
	go test -i code.google.com/p/tasked/auth
	go test code.google.com/p/tasked/auth
	go test -i code.google.com/p/tasked/htauth
	go test code.google.com/p/tasked/htauth
	go test -i code.google.com/p/tasked/htproc
	go test code.google.com/p/tasked/htproc $long
	go test -i code.google.com/p/tasked/keyval
	go test code.google.com/p/tasked/keyval
	go test -i code.google.com/p/tasked/htfile
	go test code.google.com/p/tasked/htfile
	go test -i code.google.com/p/tasked
	go test code.google.com/p/tasked $long
	chmod -Rf o+r+w+X $testdata
	chmod -Rf o+r+w+X pkg
	if [ "$testdir" != "" ]; then
		rm -rf $testdir
	fi
}

function createTestUser {
	testuser=testuser
	testpwd=testpwd
	if [ "$1" != "" ]; then testuser=$1; fi
	if [ "$2" != "" ]; then testpwd=$2; fi

	if ! grep '^'$testuser':' /etc/passwd > /dev/null; then
		useradd -p "" $testuser &> /dev/null
	fi
	echo $testuser:$testpwd | chpasswd &> /dev/null
}

case $1 in
selfcert)
	selfcert $@;;
test)
	shift
	test $@;;
testuser)
	shift
	createTestUser $@;;
*)
	defaultgo $@;;
esac
